package com.itheima.aspect;


import com.itheima.entity.Result;
import com.itheima.exception.OptimisticLockingFailureException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author suga
 * @version v1.0
 * @date 2019/8/7 7:42 PM
 * @description 目标方法的切面
 **/
@Component
@Aspect
public class RetryAspect {

    //最大重试数
    public static final int MAX_RETRY_TIMES = 3;

    //把切入方法上的注解作为切点
   @Pointcut("@annotation(com.itheima.annotation.RetryOnFailure)")
    public void retryOnFailure(){}

    @Around("retryOnFailure()")
    public Result doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {

       //方法循环3次
        Result proceed = null;
        int attempts = 0;

        while (attempts < MAX_RETRY_TIMES) {
            try {

                proceed = (Result) pjp.proceed();

                break;

            } catch (OptimisticLockingFailureException e) {

                //每次抛异常 触发事务回滚
                //    throw e;

            } catch (Exception e) {

                e.printStackTrace();

            }
            attempts++;
        }

        if (MAX_RETRY_TIMES==attempts){

            return new Result(false,"系统繁忙,请稍后再试");
        }

         return proceed;

    }
}
